<?php

namespace app\modules\weixin\controllers;

use app\common\components\BaseWebController;
use app\common\service\UrlService;

class MsgController extends BaseWebController
{
    public function actionIndex()
    {
        //加密验证
        if( !$this->checkSignature() ){
            return "error signature~~";
        }

        if( array_key_exists( "echostr",$_GET && $_GET['echostr'] ) ){//用于微信第一次验证
            return $_GET['echostr'];
        }

        //获取xml数据
        $xml_data = file_get_contents("php://input");
        $this->record_log( "[xml_data]:".$xml_data );
        if( !$xml_data ){
            return "error xml~~";
        }

        $xml_obj = simplexml_load_string( $xml_data,"SimpleXMLElement",LIBXML_NOCDATA );
        $from_username = $xml_obj->FromUserName;
        $to_username = $xml_obj->ToUserName;
        $msg_type = $xml_obj->MsyType;

        $res = ["type" => "text","data" => $this->defaultTip()];
        switch( $msg_type ){
            case 'text':
                $kw = trim( $xml_obj->Content );
                $res = $this->search( $kw );
                break;
            case 'event':
                break;
        }

        switch( $res['type'] ){
            case 'text':
                return $this->textTpl($from_username,$to_username,$res['data'] );
                break;
            case 'rich':
                return $this->richTpl( $from_username,$to_username,$res['data'] );
                break;
        }




    }

    public function search( $kw ){
        $query = Book::find()->where(['status' => 1]);
        $where_name = ['LIKE','name','%'.$kw.'%',false];
        $where_tag = ['LIKE','tags','%'.$kw.'%',false];
        $query->andWhere( ['OR',$where_name,$where_tag] );

        $res = $query->orderBy(['id'=>SORT_DESC])->limit( 3 )->all();
        $data = $res?$this->getRichXml( $res ):$this->defaultTip();
        $type = $res?"rich":"text";
        return ["type" => $type,"data" =>$data];
    }


    private function textTpl( $from_username,$to_username,$content )
    {
        $tpl = <<<EOT
        <xml> 
        <ToUserName><![CDATA[%s]]></ToUserName> 
        <FromUserName><![CDATA[%s]]></FromUserName> 
        <CreateTime>%s</CreateTime> 
        <MsgType><![CDATA[%s]]></MsgType> 
        <Content><![CDATA[%s]]></Content> 
        </xml>
EOT;
        return sprintf( $tpl,$from_username,$to_username,time(),"text",$content );
    }

    private function getRichXml( $list )
    {
        $article_count = count( $list );
        $article_content = "";
        foreach( $list as $_item ){
            $tmp_description = mb_substr(strip_tags( $_item['summary'] ),0,20,'utf-8');
            $tmp_pic_url = UrlService::buildPicUrl( "book",$_item['main_image'] );
            $tmp_url = UrlService::buildMUrl( "/product/info",['id' => $_item['id']] );
            $article_content .= "<item>
            <Title><![CDATA[{$_item['name']}]]></Title> 
            <Description><![CDATA[{$tmp_description}]]></Description>
            <PicUrl><![CDATA[{$tmp_pic_url}]]></PicUrl>
            <Url><![CDATA[{$tmp_url}]]></Url>
            </item>";
        }

        $article_body = "<ArticleCount>%s</ArticleCount><Articles>%s</Articles>";
        return sprintf( $article_body,$article_count,$article_content );
    }

    private function richTpl( $from_username,$to_username,$data ){
        $tpl = <<<EOT
    <xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[%s]]></MsgType>
    %s
    </xml>
EOT;
        return sprintf( $tpl,$from_username,$to_username,time(),$data );
    }

    private function defaultTip()
    {
        $resData = <<<EOT
没找到你想要的东西:(\n
EOT;
        return $resData;
    }

    public function checkSignature()
    {
        $signature = trim( $this->get( "signature" ) );
        $timestamp = trim( $this->get( "timestamp" ) );
        $nonce     = trim( $this->get( "nonce" ) );
        $tmpArr= array( \Yii::$app->params["weixin"]["token"],$timestamp,$nonce );
        sort( $tmpArr );
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        } else {
            return false;
        }
    }

    public function record_log( $msg )
    {
        $log = new FileTarget();
        $log->logFile = \Yii::$app->getRuntimePath().'logs/weixin_msg_'.date("Ymd").'.log';
        $request_uri = isset( $_SERVER['REQUEST_URI'] )?$_SERVER['REQUEST_URI']:'';
        $log->messages[] = [
            "[url:{$request_uri}][post:".http_build_query( $_POST )."][msg:{$msg}]",
            1,
            'application',
            microtime( true )
        ];
        $log->export();
    }
}